package zmee.pur.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.message.api.CountryCode;
import kd.bos.message.api.ShortMessageInfo;
import kd.bos.message.service.handler.MessageHandler;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.workflow.engine.msg.info.MessageInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zyj
 * @Date: 2023/7/25 15:27
 * @Description: 通知供应商: 根据供应商信息发送短信到供应商联系人电话，同时推送消息到相应用户消息中心
 */
public class PdsNoticesuppliSmsBillPlugin extends AbstractBillPlugIn {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        if ("audit".equals(operateKey)) {
            // 用来存放消息内容
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("您好，你有新的邀请函/中标通知书待确认，请及时处理，谢谢。");
            DynamicObject project = (DynamicObject) this.getModel().getValue("project");
            stringBuilder.append("\n采购组织：" + project.getDynamicObject("org").getString("name"));
            stringBuilder.append("\n寻源项目名称：" + project.getString("bidname"));
            stringBuilder.append("\n寻源项目编号：" + project.getString("billno"));
            stringBuilder.append("\n业务链接：" + "http://opc.zmeeol.com/srm/");

            // 发送消息到消息中心
            MessageInfo messageInfo = new MessageInfo();
            // 消息中心标题
            messageInfo.setMessageTitle(new LocaleString("【邀请函/中标通知书确认通知】"));
            // 消息中心内容
            messageInfo.setMessageContent(new LocaleString(stringBuilder.toString()));
            // 用来存放发送到那几个用户的消息中心去
            ArrayList<Long> userIds = new ArrayList<>();
            // 用来存放发送短信到哪几个手机号码中去
            List<String> phones = new ArrayList<>();
            // 用来存放跳转的单据id
            String openPkId = null;
            DynamicObjectCollection supplierentrys = this.getModel().getDataEntity().getDynamicObjectCollection("supplierentry");
            for (DynamicObject supplierentry : supplierentrys) {
                // 获取是否发送
                if (supplierentry.getBoolean("issend")) {
                    // 获取电话
                    String phone = supplierentry.getString("phone");
                    phones.add(phone);
                    // 设置过滤条件 通过寻源项目编码找到寻源项目单据
                    QFilter qFilter = new QFilter("billno", QCP.equals, project.getString("billno"));
                    DynamicObject[] tnd_projects = BusinessDataServiceHelper.load("tnd_project", "id, billno", new QFilter[]{qFilter});
                    // 设置过滤条件 通过电话找到对应用户
                    QFilter qFilter3 = new QFilter("phone", QCP.equals, phone);
                    DynamicObject[] users = BusinessDataServiceHelper.load("bos_user", "id,name,phone", new QFilter[]{qFilter3});
                    if (tnd_projects != null && tnd_projects.length == 1 ){
                        Long PkId = (Long) tnd_projects[0].getPkValue();
                        openPkId = PkId.toString();
                    } else {
                        this.getView().showTipNotification("未能找到对应寻源项目或者寻源项目为多个,发送短信失败！");
                        return;
                    }
                    for (DynamicObject user : users) {
                        userIds.add((Long) user.get("id"));
                    }
                }
            }

            // 设置发送消息的用户
            messageInfo.setUserIds(userIds);
            // 设置主实体编码标识
            messageInfo.setEntityNumber("pds_noticesupplier");
            // 设置业务标签
            messageInfo.setTag("发标通知供应商");
            // 设置消息类型
            messageInfo.setType("message");
            // 设置快速处理跳转的url 第一个方法获取域名
            String url = System.getProperty("domain.contextUrl") + "/?formId=tnd_project" + "&pkId=" + openPkId + "&apptype=sms";
            messageInfo.setContentUrl(url);
            messageInfo.setMobContentUrl(url);
            // 发送消息到消息中心 返回消息id
            long messageId = MessageCenterServiceHelper.sendMessage(messageInfo);

            // 发送短信
            ShortMessageInfo shortMessageInfo = new ShortMessageInfo();
            // 设置发送短信到哪些手机号码
            shortMessageInfo.setPhone(phones);
            // 设置国家代码
            shortMessageInfo.setCountryCode(CountryCode.CN);
            // 设置消息内容
            shortMessageInfo.setMessage(stringBuilder.toString());
            // 设置消息id
            shortMessageInfo.setMessageId(messageId);
            // 发送短信
            Map<String, Object> stringObjectMap = MessageHandler.sendShortMessage(shortMessageInfo);
            String code = (String) stringObjectMap.get("code");
            if (!"0".equals(code)) {
                this.getView().showTipNotification("发送短信发生错误，失败" + "错误原因: " + (String) stringObjectMap.get("description"));
            }
        }
    }
}
